<?php

namespace app\models\sms;

/**
 * This is the model class for table "sms_captcha".
 *
 * @property string $id
 * @property string $mobile
 * @property string $captcha
 * @property string $ip
 * @property string $expires_at
 * @property integer $status
 * @property string $created_time
 */
class SmsCaptcha extends \yii\db\ActiveRecord
{
    /**验证手机验证码
     * @param $mobile
     * @param $captcha
     */
    public static function checkCaptcha($mobile, $captcha)
    {
        $info = self::find()->where(["mobile" => $mobile, "captcha" => $captcha])->one();
        if ($info && strtotime($info['expires_at']) >= time()) {
            $info->expires_at = date("Y-m-d H:i:s", time() - 1);
            $info->status = 1;
            $info->save(0);
            return true;
        }
        return false;
    }

    /**生成手机验证码
     * @param $mobile
     * @param string $ip
     * @param string $sign
     * @param string $channel
     */
    public function geneCustomerCaptcha($mobile, $ip = "", $sign = "", $channel = "")
    {
        $captcha = rand(10000, 99999);

        $this->mobile = $mobile;
        $this->ip = $ip;
        $this->captcha = $captcha;
        $this->expires_at = date("Y-m-d H:i:s", time() + 60 * 10);
        $this->created_time = date("Y-m-d H:i:s");
        $this->status = 0;

        $this->SendSMS($mobile, $captcha, '宝丽汽服', 'SMS_102820005', "LTAIVmBQsQJmdMeD", "5TC0sER8cFWItzUy27Zyja6NWe6R6o");

        return $this->save(0);
    }

    //参数说明
    //$mobile 目标手机号
    //$ParamString 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。
    //$SignName 管理控制台中配置的短信签名（状态必须是验证通过）
    //$TemplateCode 管理控制台中配置的审核通过的短信模板的模板CODE（状态必须是验证通过）
    //$AccessKeyId 阿里云颁发给用户的访问服务所用的密钥ID
    //$AccessKeySecret 阿里云颁发给用户的访问服务所用的验证串
    //返回值
    //发送成功返回true,结果仅供参数，不保证完全正确
    /**
     * @param $mobile
     * @param $ParamString
     * @param $SignName
     * @param $TemplateCode
     * @param $AccessKeyId
     * @param $AccessKeySecret
     */
    private function SendSMS($mobile, $ParamString, $SignName, $TemplateCode, $AccessKeyId, $AccessKeySecret)
    {
        $url = 'http://dysmsapi.aliyuncs.com/';
        $accessKeyId = $AccessKeyId;
        $accessKeySecret = $AccessKeySecret;
        date_default_timezone_set("GMT");
        $Timestamp = date('Y-m-d\TH:i:s\Z');

        $parameters = array(
            'PhoneNumbers' => $mobile,
            'SignName' => $SignName,
            'TemplateCode' => $TemplateCode,
            'TemplateParam' => '{"code":' . $ParamString . '}',
            'OutId' => '1234',
            'RegionId' => 'cn-hangzhou',
            'AccessKeyId' => $accessKeyId,
            'Format' => 'JSON',
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureVersion' => '1.0',
            'SignatureNonce' => uniqid(),
            'Timestamp' => $Timestamp,
            'Action' => 'SendSms',
            'Version' => '2017-05-25',
        );
        $Signature = $this->computeSignature($parameters, $accessKeySecret);
        $parameters['Signature'] = $Signature;

        $res = $this->request_post($url, $parameters);
    }

    /**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     */
    function request_post($url = '', $post_data = array())
    {
        if (empty($url) || empty($post_data)) {
            return false;
        }

        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);

        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }

    /**阿里短信签名加密算法
     * @param $parameters
     * @param $accessKeySecret
     * @return string
     */
    public function computeSignature($parameters, $accessKeySecret)
    {
        ksort($parameters);
        $canonicalizedQueryString = '';
        foreach ($parameters as $key => $value) {
            $canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value);
        }
        $stringToSign = 'POST' . '&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . "&", true));
        return $signature;
    }

    protected function percentEncode($str)
    {
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }

    /**
     * @inheritdoc
     */
    public
    static function tableName()
    {
        return 'sms_captcha';
    }

    /**
     * @inheritdoc
     */
    public
    function rules()
    {
        return [
            [['expires_at', 'created_time'], 'safe'],
            [['status'], 'required'],
            [['status'], 'integer'],
            [['mobile', 'ip'], 'string', 'max' => 20],
            [['captcha'], 'string', 'max' => 10],
        ];
    }

    /**
     * @inheritdoc
     */
    public
    function attributeLabels()
    {
        return [
            'id' => 'ID',
            'mobile' => 'Mobile',
            'captcha' => 'Captcha',
            'ip' => 'Ip',
            'expires_at' => 'Expires At',
            'status' => 'Status',
            'created_time' => 'Created Time',
        ];
    }
}
